package cn.tedu._07springaop.aop;

import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.openjsse.net.ssl.OpenJSSE;
import org.springframework.stereotype.Component;

import java.util.Arrays;

/**
 * 切面类:为目标方法进行功能增强的类
 */
@Aspect
@Component
public class LogAspect {
    @Before("execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))")
    public void beforeMethod(JoinPoint joinPoint) {
        /**
         * 1.joinPoint:连接点参数;
         * 2.获取目标方法名:joinPoint.getSignature().getName();
         * 3.获取目标方法参数:joinPoint.getArgs();
         */
        String name = joinPoint.getSignature().getName();
        String args = Arrays.toString(joinPoint.getArgs());
        System.out.println("1-前置通知:" + name + "方法开始执行,参数为:" + args);
    }

    @AfterReturning(value = "execution(public int cn.tedu._07springaop.aop." +
            "CalculatorImpl.*(..))", returning = "r")
    public void afterReturningMethod(JoinPoint joinPoint, Object r) {
        String name = joinPoint.getSignature().getName();
        System.out.println("2-返回通知:" + name + "方法结束,结果为:" + r);
    }

    /**
     * 3.AfterThrowing注解:异常通知,当目标方法抛出异常时,被此方法拦截
     */
    @AfterThrowing(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))", throwing = "ex")
    public void afterThrowingMethod(JoinPoint joinPoint, Throwable ex) {
        String name = joinPoint.getSignature().getName();
        System.out.println("3.异常通知:" + name + "方法异常,提示消息为:" + ex);
    }

    /**
     * 4.After注解:后置通知,当目标彻底结束后执行
     */
    @After(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))")
    public void afterMethod(JoinPoint joinPoint) {
        String name = joinPoint.getSignature().getName();
        System.out.println("4-返回通知:" + name + "方法彻底结束后执行");
    }

    @Around(value = "execution(public int cn.tedu._07springaop.aop.CalculatorImpl.*(..))")
    public Object aroundMethod(ProceedingJoinPoint joinPoint) {
        Object result = null;
        try {
            System.out.println("环绕1-前置通知");
            result = joinPoint.proceed();
            System.out.println("环绕2-返回通知");
        } catch (Throwable e) {
            System.out.println("环绕3-异常通知");
            throw new RuntimeException(e);
        } finally {
            System.out.println("环绕4-后置通知");
        }
        return result;
    }
}
